const fs = require('fs')
const path = require('path')

const regStyle = /<style>[\s\S]*<\/style>/;

const regScript = /<script>[\s\S]*<\/script>/;
//对index.html 读取流

fs.readFile(path.join(__dirname, 'index.html'), 'utf8', (err, Str) => {
    if (err) return console.log('读取文件失败' + err.message);
    //console.log(Str);
    resolveStr(Str, 'css');
    resolveStr(Str, 'js');
    relHtml(Str);
})

function resolveStr(dataStr, re) {
    let newRe = null;
    if (re == 'css') {
        let regcs = regStyle.exec(dataStr);
        newRe = regcs[0].replace('<style>', '').replace('</style>', '');
    } else {
        let regcs = regScript.exec(dataStr);
        newRe = regcs[0].replace('<script>', '').replace('</script>', '');
    }
    //写入css
    fs.writeFile(path.join(__dirname, 'index.' + re), newRe, (err) => {
        if (err) return console.log('写入' + re + '失败！');
        console.log('写入' + re + '成功');
    })
}

function relHtml(dataStr) {
    const newHTML = dataStr.replace(regStyle, '<link rel="stylesheet" href="./index.css">').replace(regScript, ' <script src="./index.js"></script>');
    fs.writeFile(path.join(__dirname, 'index.html'), newHTML, (err) => {
        if (err) return console.log('写入index.html失败' + err.message);
        console.log("写入index.html成功");

    })
}